package com.qianlou.qrcode.servlets;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/generate")
public class GenerateQRCode extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
            doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String text = req.getParameter("text");

            Map map = new HashMap();
            //设置二维码的误差级别
            map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            //设置二维码的字符集
            map.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //设置二维码四周的空白区域
            map.put(EncodeHintType.MARGIN, 1);

            //创建zxing的核心对象，MultiFormatWriter是生成二维码的核心类
            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, 200, 200, map);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }
            ServletOutputStream out = resp.getOutputStream();
            ImageIO.write(image, "png", out);
            out.flush();
            out.close();
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
}
